<?php
namespace app\admin\controller;

use app\common\BaseAdminController;
use app\model\Permission as ModelPermission;

class Permission extends BaseAdminController
{
    public function list($pageNum = 1, $pageSize = 10)
    {
        $query = ModelPermission::order('id', 'asc')
            ->page($pageNum, $pageSize);

        $list  = $query->select();
        $total = $query->count();

        return json([
            'code' => 200,
            'msg'  => '查询成功',
            'data' => [
                'list'  => $list,
                'total' => $total,
            ],
        ]);
    }

    public function add()
    {
        $data     = $this->request->post();
        $validate = new \app\validate\Permission();
        if (! $validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        $exists = ModelPermission::where('name', $data['name'])->find();
        if ($exists) {
            return json(['code' => 400, 'msg' => '该权限已存在']);
        }

        $permission = new ModelPermission();
        $permission->save($data);

        return json(['code' => 200, 'msg' => '添加成功']);
    }

    public function edit()
    {
        $data     = $this->request->post();
        $validate = new \app\validate\Permission();
        if (! $validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        $permission = ModelPermission::where('id', $data['id'])->find();
        $permission->save($data);

        return json(['code' => 200, 'msg' => '添加成功']);
    }
}
